<template>
	<view
		class="chat-input-container"
		@click.stop
		@touchend.stop
		:style="{
			width: systemInfo.windowWidth + 'px'
		}"
	>
		<!-- 输入区域 -->
		<view class="input-bar">
			<!-- 文本/语音切换按钮 -->
			<view class="switch-btn" @click="switchInputMode">
				<uni-icons :type="inputMode === 'text' ? 'mic' : 'font'" size="28"></uni-icons>
			</view>

			<!-- 输入框区域 -->
			<view class="input-container">
				<textarea
					v-if="inputMode === 'text'"
					class="text-input"
					v-model="inputContent"
					placeholder="请输入消息..."
					@focus="onInputFocus"
					@blur="onInputBlur"
					ref="inputref"
					:autoHeight="true"
					:confirm-hold="true"
					:adjust-position="true"
					placeholder-style="color:#eaeaea;"
					:cursor-spacing="6"
					@confirm="sendMessage"
					:style="{ width: systemInfo.windowWidth * 0.55 + 'px' }"
				></textarea>
				<!-- 语音输入 - 已移除所有 .prevent 修饰符 -->
				<view
					v-if="inputMode === 'mic'"
					class="voice-input"
					:class="{ 'voice-input-recording': recordShow }"
					:style="{ width: systemInfo.windowWidth * 0.55 + 'px' }"
					@longpress="handleRecordShow"
					@touchend="handleRecordHide"
					@touchstart="touchstart"
					@touchmove.prevent="handleTouchMove"
				>
					<text class="voice-tip">按住说话</text>
					<view class="record-btn-wrapper">
						<view class="record-btn" :class="{ recording: recordShow }">
							<uni-icons type="mic" size="26" :color="recordShow ? '#fff' : '#666'"></uni-icons>
						</view>
					</view>
				</view>
			</view>

			<!-- 功能按钮区 -->
			<view class="func-btns" :style="{ width: systemInfo.windowWidth * 0.3 + 'px' }">
				<view class="func-btn" @click="toggleEmojiPanel">
					<image src="/static/emjoy.png" mode="widthFix" class="emoji-icon"></image>
				</view>
				<view v-if="!inputContent.trim()" class="func-btn" @click="toggleToolPanel">
					<uni-icons :class="showToolPanel ? 'rotate-icon' : 'default-icon'" type="plus" size="30"></uni-icons>
				</view>

				<!-- 发送按钮 -->
				<button v-if="inputMode === 'text' && inputContent.trim()" class="send-btn" @click="sendMessage">
					<text class="send-text">发送</text>
				</button>
			</view>
		</view>

		<!-- 工具面板 -->
		<view class="tool-panel" v-if="showToolPanel" :style="{ width: systemInfo.windowWidth }">
			<view class="tool-grid">
				<view class="tool-item" @click="chooseImage">
					<uni-icons type="camera" size="30" color="#666"></uni-icons>
					<text class="tool-name">图片</text>
				</view>
				<view class="tool-item" @click="chooseVideo">
					<uni-icons type="videocam" size="30" color="#666"></uni-icons>
					<text class="tool-name">视频</text>
				</view>
				<view class="tool-item" @click="chooseFile">
					<uni-icons type="folder-add" size="30" color="#666"></uni-icons>
					<text class="tool-name">文件</text>
				</view>
				<view class="tool-item" @click="showLocation">
					<uni-icons type="location" size="30" color="#666"></uni-icons>
					<text class="tool-name">位置</text>
				</view>
				<view class="tool-item" @click="showRedPacket">
					<uni-icons type="email-filled" size="30" color="#ff0000"></uni-icons>
					<text class="tool-name">红包</text>
				</view>
				<view class="tool-item" @click="sendShop">
					<uni-icons type="shop" size="30" color="#666"></uni-icons>
					<text class="tool-name">店铺</text>
				</view>
				<view class="tool-item" @click="sendGood">
					<uni-icons type="gift" size="30" color="#666"></uni-icons>
					<text class="tool-name">卖货</text>
				</view>
			</view>
		</view>

		<!-- 表情面板 -->
		<view class="emoji-panel" v-if="showEmojiPanel">
			<view class="emoji-grid" :style="{ width: systemInfo.windowWidth + 'px' }">
				<view class="emoji-item" v-for="(emoji, index) in currentPageEmojis" :key="index" @click="insertEmoji(emoji)">
					<text class="emoji-text">{{ emoji }}</text>
				</view>
			</view>
		</view>

		<!-- 使用修复后的 InputDialog 组件 -->
		<input-dialog :isShow.sync="isDialogShow" @confirm="confirm" @cancel="cancel"></input-dialog>
		<recordManger :toTarget="toTarget"  v-if="recordShow"></recordManger>
	</view>
</template>

<script>
import checkPermissions from '@/utils/checkPermissions';
import { Images, Video } from '../utils/media.js';
import MessageSender from '../utils/MessageSender.js';
import InputDialog from './InputDialog.vue'; // 引入修复后的组件
const linli = uniCloud.importObject('linliChat', { customUI: true });
import recordManger from './recordManger.vue';

export default {
	name: 'ChatInput',
	components: {
		InputDialog, // 注册组件
		recordManger
	},

	data() {
		return {
			// 输入相关
			inputContent: '',
			inputRows: 1,
			maxInputRows: 4,
			inputMode: 'text', // text/mic
			showToolPanel: false,

			absMoveY: 0, // 垂直移动距离
			// 表情相关
			showEmojiPanel: false,
			isDialogShow: false,
			keyboardHeight: 0,

			fileIds: [],
			emojis: ['😀', '😁', '😂', '🤣', '😃', '😄', '😅', '😆', '😊', '😋', '😎', '😍', '😘', '🥰', '😗', '😙', '😚', '☺️', '🙂', '🙃'],
			currentEmojiPage: 0,
			emojiPerPage: 20,

			// 语音相关

			systemInfo: {},
			startX: 0,
			startY: 0,

			emojiPanelHeight: 0,
			sendParam: {},
			bottom: 0,
			safeAreaBottom: 0,
			isInputFocused: false,
			inputBlurTimer: null,
			recordShow:false
		};
	},
	computed: {
		// 计算表情分页
		emojiPages() {
			return Math.ceil(this.emojis.length / this.emojiPerPage);
		},
		// 当前页表情
		currentPageEmojis() {
			const start = this.currentEmojiPage * this.emojiPerPage;
			return this.emojis.slice(start, start + this.emojiPerPage);
		},
		keyHightEvent() {
			return this.showToolPanel || this.showEmojiPanel || this.keyboardHeight > 0;
		},
		toTarget() {
			return this.$store.state.msg.toTarget;
		},
		storeData() {
			return this.$store.state.msg;
		}
	},
	watch: {
		keyHightEvent: {
			handler(newVal) {
				uni.$emit('keyHightEvent', newVal);
			},
			immediate: true
		}
	},

	mounted() {
		this.systemInfo = uni.getSystemInfoSync();
		this.safeAreaBottom = this.systemInfo.safeAreaInsets?.bottom || 0;

		uni.$on('mainPageClickEven', (res) => {
			this.showEmojiPanel = false;
			this.showToolPanel = false;
			uni.hideKeyboard();
		});
		uni.onKeyboardHeightChange((res) => {
			this.keyboardHeight = res.height;
		});
	},

	destroyed() {
		uni.$off('mainPageClickEven');
	},

	methods: {
		// 切换输入模式
		switchInputMode() {
			this.inputMode = this.inputMode === 'text' ? 'mic' : 'text';
			if (this.inputMode === 'mic') {
				const hasPermission = checkPermissions('record', '麦克风');
				if (!hasPermission) {
					uni.showToast({ title: '需要麦克风权限才能录音', icon: 'none' });
					this.inputMode = 'text'; // 无权限切回文本模式
				}
			}
		},

		// 切换工具面板
		toggleToolPanel() {
			uni.hideKeyboard();
			this.showToolPanel = !this.showToolPanel;
			this.showEmojiPanel = false;
		},
		// 切换表情面板
		toggleEmojiPanel() {
			uni.hideKeyboard();
			this.showEmojiPanel = !this.showEmojiPanel;
			this.showToolPanel = false;
		},

		// 插入表情
		insertEmoji(emoji) {
			this.inputContent += emoji;
		},

		// 输入框聚焦事件
		onInputFocus() {
			this.isInputFocused = true;
			this.showEmojiPanel = false;
			this.showToolPanel = false;
		},

		// 输入框失焦事件
		onInputBlur() {},

		// 发送消息
		async sendMessage() {
			try {
				const msg = this.inputContent.trim();
				if (msg) {
					const messageSender = new MessageSender(this.storeData);
					const sendmsg = await messageSender.sendText(this.toTarget, msg);
					this.$emit('sendText', sendmsg);
					this.inputContent = '';
					this.inputRows = 1;
				}
			} catch (e) {
				console.error(e);
				uni.showToast({ title: '发送失败', icon: 'none' });
			}
		},

		// 选择图片
		async chooseImage() {
			try {
				const res = await Images();
				console.log('图片', res);
				this.sendParam = { type: 'media', data: res };
				this.isDialogShow = true;
				this.showToolPanel = false;
			} catch (err) {
				console.error('选择图片失败', err);
				uni.showToast({ title: '选择图片失败', icon: 'none' });
			}
		},

		// 选择视频
		async chooseVideo() {
			try {
				this.showToolPanel = false;
				this.sendParam.type = 'video';
				const res = await Video();
				if (res.code) {
					this.sendParam = { ...this.sendParam, data: res.videoPath };
					this.isDialogShow = true;
				}
			} catch (err) {
				console.error('选择视频失败', err);
				uni.showToast({ title: '选择视频失败', icon: 'none' });
			}
		},

		// 选择文件
		chooseFile() {
			uni.chooseMessageFile({
				count: 1,
				type: 'file',
				success: (res) => {
					console.log('选择文件', res);
					this.$emit('sendFile', res.tempFiles[0]);
					this.showToolPanel = false;
				},
				fail: (err) => {
					console.error('选择文件失败', err);
					uni.showToast({ title: '选择文件失败', icon: 'none' });
				}
			});
		},

		// 确认发送（图片/视频）
		async confirm(e) {
			try {
				const messageSender = new MessageSender(this.storeData);
				if (this.sendParam.type === 'media') {
					const msg = await messageSender.sendMedia(this.toTarget, { paths: this.sendParam.data, content: e });
					console.log('发送成功', msg);
					this.$emit('sendImages', msg);
				}
				if (this.sendParam.type === 'video') {
					const msg = await messageSender.sendVideo(this.toTarget, this.sendParam.data, e);
					this.$emit('sendVideo', msg);
				}
				this.isDialogShow = false;
			} catch (e) {
				console.error(e);
				uni.showToast({ title: '发送失败', icon: 'none' });
			}
		},

		// 取消发送（图片/视频）
		async cancel() {
			let fileIds = [];
			try {
				if (this.sendParam.type === 'media' && this.sendParam.data) {
					fileIds = this.sendParam.data.map((item) => item.fileID);
				}
				if (this.sendParam.type === 'video' && this.sendParam.data) {
					// 根据实际返回的数据结构调整
					fileIds = [this.sendParam.data.fileID];
				}
				if (fileIds.length > 0) {
					await linli.deleFile(fileIds);
				}
			} catch (e) {
				console.log('取消时删除文件失败:', e);
			} finally {
				this.isDialogShow = false;
			}
		},
		handleRecordShow() {
			uni.vibrateShort();
			this.recordShow=true
		},
		touchstart(e) {
			this.startY = e.touches[0].pageY;
		},
		handleTouchMove(e) {
			// #ifndef APP-NVUE
			e.preventDefault();
			e.stopPropagation();
			//#endif
			const currentY = e.touches[0].pageY;
			uni.$emit('recordCancel', currentY - this.startY < -50);
		},
		handleRecordHide() {
			this.recordShow=false
		},

		handleTouchEnd(e) {
			this.recordShow=false
		},

		// 跳转店铺
		sendShop() {
			this.showToolPanel = false;
			uni.navigateTo({ url: '/pages/sendShop/sendShop' });
		},

		// 跳转卖货
		sendGood() {
			this.showToolPanel = false;
			uni.navigateTo({ url: '/pages/draft/draft' });
		},

		// 显示位置（占位）
		showLocation() {
			this.showToolPanel = false;
			uni.showToast({ title: '位置功能开发中', icon: 'none' });
		},

		// 显示红包（占位）
		showRedPacket() {
			this.showToolPanel = false;
			uni.showToast({ title: '红包功能尚未开放', duration: 2000, position: 'center' });
		}
	}
};
</script>

<style lang="scss" scoped>
/* 基础容器 */
.chat-input-container {
	display: flex;
	flex-direction: column;
	background-color: #fff;
	padding: 15rpx 16rpx;
	box-sizing: border-box;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	z-index: 10200;
}

.emoji-icon {
	width: 45rpx;
	height: 45rpx;
}

/* 输入栏 */
.input-bar {
	display: flex;
	flex-direction: row;
	width: 750rpx;
	align-items: center;
	background-color: #fff;
	padding: 5rpx 16rpx;
	border-top: 1rpx solid #eee;
}

/* 切换按钮 */
.switch-btn {
	width: 48rpx;
	height: 48rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 8rpx;
}

/* 输入容器 */
.input-container {
	flex: 1;
	display: flex;
	align-items: center;
}

/* 文本输入框 */
.text-input {
	height: 50rpx;
	font-size: 32rpx;
	line-height: 48rpx;
	padding: 5rpx 10rpx;
	border-radius: 25rpx;
	border: 1rpx solid rgba(0, 0, 0, 0.05);
	background-color: #f9f9f9;
}

/* 语音输入区 */
.voice-input {
	height: 50rpx;
	flex: 1;
	border-radius: 25rpx;
	padding: 10rpx 20rpx;
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: center;
	background-color: #f7f7f7;
}

.voice-input-recording {
	background-color: #eaeaea;
}
.record-btn-wrapper {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.voice-tip {
	font-size: 28rpx;
	color: #666;
	margin-right: 16rpx;
}

.record-btn {
	width: 56rpx;
	height: 56rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #f1f1f1;
}

.recording {
	background-color: #ff4d4f;
	box-shadow: 0 0 20rpx rgba(255, 77, 79, 0.5);
}

/* 功能按钮区 */
.func-btns {
	display: flex;
	flex-direction: row;
	justify-content: space-around;
	padding: 0 20rpx;
	align-items: center;
	margin-left: 8rpx;
}

.func-btn {
	width: 52rpx;
	height: 52rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-left: 8rpx;
}

/* 发送按钮 */
.send-btn {
	width: 120rpx;
	height: 52rpx;
	line-height: 48rpx;
	background-color: #07c160;
	border-radius: 24rpx;
	margin-left: 16rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.send-text {
	color: #fff;
	font-size: 24rpx;
}

/* 表情面板 */
.emoji-panel {
	height: 222px;
	background-color: #fff;
	padding: 8rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.emoji-grid {
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
	align-items: center;
	justify-content: flex-start;
}

.emoji-item {
	height: 89rpx;
	width: 89rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.emoji-text {
	font-size: 42rpx;
}

/* 工具面板 */
.tool-panel {
	display: flex;
	height: 222px;
	background-color: #fff;
	padding: 16rpx 0;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.tool-grid {
	display: flex;
	flex-direction: row;
	width: 750rpx;
	flex-wrap: wrap;
}

.tool-item {
	width: 180rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 16rpx 0;
}

.tool-name {
	font-size: 24rpx;
	color: #666;
	margin-top: 8rpx;
}

/* 录音提示 */
.voice-recording {
	width: 240rpx;
	height: 280rpx;
	background-color: rgba(0, 0, 0, 0.7);
	border-radius: 24rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}
.voice-recording-mask {
	position: fixed;
	left: 0;
	top: 0;
	bottom: 0;
	right: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 10000;
	display: flex;
	align-items: center;
	justify-content: center;
}

.recording-circle {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	background-color: #ff4d4f;
	margin-bottom: 24rpx;
	animation: pulse 1.5s infinite;
}

.recording-circle-cancel {
	background-color: #666;
	animation: none;
}

/* #ifndef APP-PLUS-NVUE */
@keyframes pulse {
	0% {
		transform: scale(1);
		opacity: 1;
	}
	50% {
		transform: scale(1.05);
		opacity: 0.8;
	}
	100% {
		transform: scale(1);
		opacity: 1;
	}
}
/* #endif */

.recording-text {
	color: #fff;
	font-size: 32rpx;
	margin-bottom: 8rpx;
}

.timer {
	color: #fff;
	font-weight: 600;
	font-size: 36rpx;
	margin-bottom: 16rpx;
}

.record-cancel {
	font-size: 24rpx;
	color: #fff;
}

/* 图标旋转样式 */
/* #ifndef APP-PLUS-NVUE */
.rotate-icon {
	transform: rotate(45deg);
	transition: transform 0.3s ease;
}
.default-icon {
	transition: transform 0.3s ease;
}
/* #endif */
</style>
